package com.crnn.smart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crnn.smart.entity.Role;
import com.crnn.smart.entity.User;
import com.crnn.smart.mapper.RoleMapper;
import com.crnn.smart.mapper.UserMapper;
import com.crnn.smart.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOneByName(username);
        Set<Role> roles = roleMapper.getRoleByUserId(user.getId());
        if (roles != null && roles.size() > 0) {
            user.setAuthorities(roles);
        }
        roleMapper.getRoleByUserId(user.getId());

        return user;
    }

    @Override
    public IPage<User> getUsers(){
        IPage<User> userPage = new Page<>(1, 20);
        IPage<User> users = userMapper.selectPage(userPage, null);
        return users;
    }

    @Override
    public IPage<User> getUserByName(String name) {
        IPage<User> userPage = new Page<>(1, 20);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", name);
        IPage<User> users = userMapper.selectPage(userPage, queryWrapper);
        return users;
    }

}
